package com.chb.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.chb.interceptor.FillMetaObjectHandler;
import com.chb.properties.MybatisPlusProperties;
import com.chb.properties.TenantProperties;
import com.chb.properties.TestProperties;
import com.chb.tenant.TenantHandler;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @description:
 * @author: CHB
 * @create: 2022-04-12 14:15
 **/
@SpringBootConfiguration
@Configuration(proxyBeanMethods = false)
@MapperScan("com.chb.*.mapper")
@EnableConfigurationProperties(value = {MybatisPlusProperties.class, TenantProperties.class, TestProperties.class})
public class MyBatisPlusConfiguration {

    /**
     * 自定义租户处理器
     *
     * @return TenantHandler
     */
    @Bean
    @ConditionalOnMissingBean(TenantLineHandler.class)
    public TenantLineHandler tenantLineHandler(TenantProperties properties) {
        return new TenantHandler(properties);
    }

    /**
     * mybatis-plus 拦截器集合
     */
    @Bean
    @ConditionalOnMissingBean(MybatisPlusInterceptor.class)
    public MybatisPlusInterceptor mybatisPlusInterceptor(MybatisPlusProperties mybatisPlusProperties, TenantLineHandler tenantLineHandler) {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        // 配置租户拦截器
       // interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(tenantLineHandler));
        // 配置分页拦截器
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
        paginationInnerInterceptor.setMaxLimit(mybatisPlusProperties.getPageLimit());
        paginationInnerInterceptor.setOverflow(mybatisPlusProperties.getOverflow());
        interceptor.addInnerInterceptor(paginationInnerInterceptor);
        return interceptor;
    }

    /**
     * 自动填充创建时间和修改时间处理器
     * @return
     */
    // @Bean(name = "fillMetaObjectHandler")
    public FillMetaObjectHandler fillMetaObjectHandler() {
        return new FillMetaObjectHandler();
    }
}
